<?php
/**
 * forgotpass.php
 * 
 * This file contains the code for the Forgot Password webpage.
 */
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];

require_once 'interface.php';
webpageDoctype();
print_html_title("Member System - Forgot Password");
webpageMetaAndBodyStart();
echo "<p><div align='center'>";
		if(strlen($username) <= 0 && strlen($userid) <= 0) {
			if($_POST['resetbtn'] === "Reset Password"){
				//get the form data
				$user = $_POST['user'];
				$email = $_POST['email'];
				
				//make sure info provided
				if (strlen($user) > 0) {
							//connect
							require("./connect.php");
							
							$query = mysql_query("SELECT * FROM users WHERE username='$user'");
							$numrows = mysql_num_rows($query);
							if ($numrows == 1){
								//get info about account
								$row = mysql_fetch_assoc($query);
								
									//generate password
									$pass = rand();
									$pass = md5($pass);
									$pass = substr($pass, 0, 15);
									$password = $pass;
									
									//updating pw
									mysql_query("UPDATE users SET password='$password' WHERE username='$user'");
									
									//make sure pw change
									$query = mysql_query("SELECT * FROM users WHERE username='$user'");
									$numrows = mysql_num_rows($query);
									if($numrows == 1){
										
										echo <<<EOL
										<div align="center">
										<p>
										<h3>
										Your password has been reset. Your new password is below:<br/>
										$pass
										</h3>
										</p>
										</h2>
EOL;
									}else{
										forgot_password_form("An error has occured and the password was not reset.<br/>");
									}
									
							}else {
								forgot_password_form("The username was not found.<br/>");
							}
							
							mysql_close($con);
				}else{
					forgot_password_form("Please enter your username.<br/>");
				}
				
			}else{
				forgot_password_form("");
			}
		}else{
			echo "Please logout to view this page.";
		}
echo "</div></p>";
webpageFooter();

function forgot_password_form($errorMsg) {
	echo <<<EOL
	<form action='./forgotpass.php' method='post'>
	<h2>Forgot Password</h2>
	<br/>
	$errorMsg
	<table>
	<tr>
		<td>Username:</td>
		<td><input type='text' name='user' /></td>
	</tr>
	<tr>
		<td></td>
		<td><input type='submit' name='resetbtn' value='Reset Password' /></td>
	</tr>
	</table>
	</form>
EOL;
}
?>
